package com.noble.meether.notify;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.library.utils.JsonUtil;
import com.noble.glamour.ui.utils.CheckIntervalTimeUtil;
import com.noble.library.log.PLogger;
import com.noble.library.log.PSP;
import com.noble.library.media.MediaUtil;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.utils.ScreenUtils;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.chat.msgtype.base.BaseMessage;
import com.noble.meether.chat.ui.imui.IMActivity;
import com.noble.meether.notify.util.NotifyUtil;

import org.json.JSONObject;

import java.util.Calendar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 消息通知管理manager
 */
public class NotifyMgr implements ModuleBase {
    private Executor notifyExecutor = Executors.newSingleThreadExecutor();  // 通知线程
    private CheckIntervalTimeUtil interval = new CheckIntervalTimeUtil();

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    /**
     * @return 判断是否在睡眠模式的区间范围
     */
    public static Boolean isInSleep() {
        if (PSP.getInstance().getBoolean(Constant.SETTING_SLEEP_MESSAGE, Constant.SETTING_SLEEP_MESSAGE_DEFAULT)) {
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            return hour < 8 || hour >= 22;
        }
        return false;
    }

    //------------------ 新消息通知 --------------------

    /**
     * 展示通知： 对位接口调用
     */
    public void startNotify(final BaseMessage message) {
        if (message == null) return;
        PLogger.d("---onChatUpdate--->sendId：" + message.getSuidTo()
                + "，message：" + message.getJsonStr());

        if (message.getUidTo() != App.uid || message.getLuidFrom() <= 0) return;
        notifyExecutor.execute(() -> showNotify(message));
    }

    //进行悬浮窗通知的消息类型
    private final int NOTIFY_COMMON = MessageConstant.MSG_ID_TEXT;      //文本消息
    private final int NOTIFY_IMAGE = MessageConstant.MSG_ID_PIC;        //图片消息
    private final int NOTIFY_VIDEO = MessageConstant.MSG_ID_VIDEO;      //小视频消息
    private final int NOTIFY_GIFT = MessageConstant.MSG_ID_GIFT;        //礼物消息

    /**
     * 进行聊天消息通知
     */
    private void showNotify(final BaseMessage message) {
        if (!PSP.getInstance().getBoolean(Constant.SETTING_MESSAGE, Constant.SETTING_MESSAGE_DEFAULT)) {
            return;
        }
        final int type = message.getMsgType();
        if (type != NOTIFY_COMMON && type != NOTIFY_GIFT && type != NOTIFY_IMAGE && type != NOTIFY_VIDEO) {
            return;
        }
        MsgMgr.getInstance().runOnUiThread(() -> viewPrivacy(message, getContent(type, message.getContent())));
    }

    /**
     * 根据消息类型展示提示内容
     *
     * @param type 消息类型
     * @return 提示内容
     */
    private String getContent(int type, String msgContent) {
        String content;
        if (type == NOTIFY_IMAGE) {
            content = "给您发了一个图片消息,请查收!";
        } else if (type == NOTIFY_VIDEO) {
            content = "给您发了一个视频消息,请查收!";
        } else if (type == NOTIFY_GIFT) {
            content = "给您发了一个礼物消息,请查收!";
        } else {
            JSONObject object = JsonUtil.getJsonObject(msgContent);
            content = object.optString("Text");
        }
        return content;
    }

    /**
     * 界面展示
     */
    private void viewPrivacy(final BaseMessage baseMessage, final String content) {
        if (App.isForeground()  // 在前台
                || ModuleMgr.getRtcEnginMgr().getPermissionStatus()) {// 处于音视频权限申请状态， 不进行应用外弹框
            noticeRemind();
            return;
        }
        ModuleMgr.getCenterMgr().reqOtherInfo(baseMessage.getLuidFrom(), response -> {
            if (!response.isOk()) {
                PLogger.d("------>个人资料查询失败, uid: " + baseMessage.getLuidFrom());
                return;
            }
            final UserDetail userDetail = (UserDetail) response.getBaseData();
            PLogger.d("---文本消息提示--->type：" + baseMessage.getMsgType() + "，content：" + content);
            //锁屏状态，锁屏弹窗
            if (ScreenUtils.isScreenLock(App.context) && (App.isKeyguard == App.AppKeyguard.KG_INIT || App.isKeyguard == App.AppKeyguard.KG_SCREEN_OFF)) {
                LockScreenMgr.getInstance().setChatData(userDetail, baseMessage, content);
                popupActivity();
                noticeRemind();
                return;
            }
            NotifyUtil.getInstance().notifyShowIMActivy(userDetail, content);
        });
    }

    //------------------------------------------------------ 提示 --------------------------------------
    private long notifyTime = -1;//控制消息提示时间，3s之后执行一次提示

    /**
     * 进行新消息提示
     */
    private void noticeRemind() {
        boolean instanceOfChat = App.getActivity() instanceof IMActivity;
        if (!instanceOfChat && (System.currentTimeMillis() - notifyTime > 3 * 1000)) {
            notifyTime = System.currentTimeMillis();
            playSound();
            vibrator();
        }
    }

    /**
     * 弹框限制
     */
    private boolean checkInterval() {
        if (interval == null) interval = new CheckIntervalTimeUtil();
        return !interval.check(Constant.FOUR_HOUR_TIME);
    }

    /**
     * 震动
     */
    public void vibrator() {
        if (PSP.getInstance().getBoolean(Constant.SETTING_VIBRATION, Constant.SETTING_VIBRATION_DEFAULT)) {
            MediaUtil.vibrator(App.getContext());
        }
    }

    /**
     * 响铃
     */
    public void playSound() {
        if (PSP.getInstance().getBoolean(Constant.SETTING_VOICE, Constant.SETTING_VOICE_DEFAULT)) {
            MediaUtil.playSound(App.getContext());
        }
    }

    /**
     * 弹窗
     */
    private void popupActivity() {
        LockScreenMgr.getInstance().popupActivity(/*!isInSleep()*/true);
    }
}
